<template>
  <div class="staffUse">
    <!-- 员工库存占用 -->
    <div class="contentView">
      <div class="herdertop">
        <img src="../../assets/top.png" alt="" class="topImg" />
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>员工管理</el-breadcrumb-item>
          <el-breadcrumb-item>员工资源占用</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div
        class="contentBox"
        v-loading="isloading"
        element-loading-text="数据加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-custom-class="loading_color"
        style="width: 100%;"
      >
        <div class="tableTop1">
          <div class="top1Left">员工资源占用</div>
          <div class="top1Right"></div>
        </div>
        <div class="tableTop2">
          <div class="top2left">
            <div class="day">
              <div style="cursor:pointer;margin-right:8px;" @click="dayPrev">
                <i class="el-icon-arrow-left"></i>
              </div>
              <div class="weekdate">{{ daystarttime }}</div>
              <div style="cursor:pointer;margin-left:8px;" @click="dayNext">
                <i class="el-icon-arrow-right"></i>
              </div>
            </div>
            <div class="chooseCity" style="margin-right:15px;">
              <span>城市：</span>
              <el-select
                v-model="chooseCityCode"
                clearable
                placeholder="请选择城市"
                :popper-append-to-body="false"
                @change="changeCityCode"
              >
                <el-option
                  v-for="item in cityAndBusinessOptions"
                  :key="item.cityCode"
                  :label="item.cityName"
                  :value="item.cityCode"
                >
                </el-option>
              </el-select>
            </div>
            <div class="chooseBusiness" style="margin-right:15px;">
              <span>商圈：</span>
              <el-select
                v-model="chooseBusinessCode"
                clearable
                placeholder="请选择商圈"
                :popper-append-to-body="false"
                @visible-change="getBusinessOptions"
              >
                <el-option
                  v-for="item in currentBusinessOptions"
                  :key="item.areaCode"
                  :label="item.areaName"
                  :value="item.areaCode"
                >
                </el-option>
              </el-select>
            </div>
            <div class="staffName" style="width:65px;font-size:12px;">
              员工名称：
            </div>
            <el-input
              placeholder="员工姓名"
              v-model="staffName"
              class="staffInput1"
            >
            </el-input>
            <div
              class="staffName"
              style="width:80px;font-size:12px;margin-left:10px;"
            >
              员工手机号：
            </div>
            <el-input
              placeholder="员工手机号"
              v-model="staffPhone"
              class="staffInput"
              maxlength="11"
            >
            </el-input>
          </div>
          <div class="top2right">
            <el-button class="searchButton" @click="searchTable"
              >查询</el-button
            >
            <el-button class="searchButton" @click="clearData">清除</el-button>
          </div>
        </div>
        <div class="teble">
          <div class="table3Box" v-show="isShowTable">
            <el-table
              :data="tableData"
              border
              :cell-class-name="changeTrStyle"
              @cell-click="cellClick"
              class="table3"
              ref="table3"
              id="table3Id"
              highlight-current-row
            >
              <el-table-column
                prop="staffName"
                label="姓名/时间"
                width="100"
                fixed
              >
                <template slot-scope="scope">
                  {{ scope.row.staffName }}
                </template>
              </el-table-column>
              <el-table-column
                v-for="(item, index) in columnData"
                :key="index"
                :label="item.day"
                show-overflow-tooltip
                width="40"
              >
                <template slot-scope="scope">
                  <!-- 无 -->
                  <!-- <span>{{scope.row.index}}</span> -->
                  <div
                    v-if="
                      scope.row.allStaffSchedulingVoList[index].staffStatus == 3
                    "
                  >
                    <a-checkbox
                      class="three"
                      :checked="checkArray[scope.row.index][index].checked"
                      @change="
                        changeCheckBoxValue($event, scope.row.index, index)
                      "
                    ></a-checkbox>
                  </div>
                  <div
                    v-if="
                      scope.row.allStaffSchedulingVoList[index].staffStatus == 1
                    "
                  >
                    <img src="./imgs/1.png" style="vertical-align:middle" />
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="nomessage" v-show="!isShowTable">
            <span>暂无数据</span>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="确认占用时间"
      :visible.sync="confirmDialogShow"
      width="50%"
      @closed="closedConfirmDialog"
      :close-on-click-modal="false"
    >
      <div class="staffName" style="margin-bottom:20px;padding-left:38px;">
        <span>员工姓名：</span>
        <span>{{
          this.staffRestTimeArray[0] ? this.staffRestTimeArray[0].staffName : ""
        }}</span>
      </div>
      <div style="margin-bottom:10px;">
        <span style="margin-left:38px;">{{
          `开始时间：${
            this.staffRestTimeArray[0] ? this.staffRestTimeArray[0].date : ""
          } ${
            this.staffRestTimeArray[0] ? this.staffRestTimeArray[0].time : ""
          }`
        }}</span>
        <span style="margin-left:60px;">{{
          `结束时间：${
            this.staffRestTimeArray[1] ? this.staffRestTimeArray[1].date : ""
          } ${
            this.staffRestTimeArray[1] ? this.staffRestTimeArray[1].time : ""
          }`
        }}</span>
      </div>
      <div>
        <el-form
          ref="form"
          :model="form"
          label-width="120px"
          class="staffUseElForm"
          label-position="right"
        >
          <el-form-item label="选择占用类型：">
            <el-radio-group v-model="form.useType">
              <el-radio label="0">出勤类</el-radio>
              <el-radio label="1">缺勤类</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择占用原因：">
            <el-radio-group v-model="form.useReason">
              <el-radio label="0">请假</el-radio>
              <el-radio label="1">调休</el-radio>
              <el-radio label="2">培训</el-radio>
              <el-radio label="3">开会</el-radio>
              <el-radio label="4">其他</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="添加备注：">
            <el-input
              type="textarea"
              v-model="form.staffUseTip"
              maxlength="200"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closedConfirmDialog">取 消</el-button>
        <el-button
          type="primary"
          @click="updateStaffSchedulingLeave"
          :loading="isButtonLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToday, getAllDate } from "./utils";
import moment from "moment";
import { tableData, oneCheckItem } from "./mockData";
import { v4 as uuidv4 } from "uuid";
export default {
  inject: ["reload"],
  data() {
    return {
      uuidv4,
      isloading: false,
      chooseCityCode: "", // 选择城市
      cityAndBusinessOptions: [], // 城市商圈总枚举
      currentBusinessOptions: [], // 当前商圈枚举
      chooseBusinessCode: "", // 选择商圈
      staffCode: "", // 员工code
      staffName: "", // 员工姓名
      staffPhone: "", // 员工手机号
      daystarttime: "", // 查询date
      tableData: [
        {
          allStaffSchedulingVoList: []
        }
      ],
      checkArray: [],
      staffRestTimeArray: [],
      confirmDialogShow: false, // 确定弹框
      form: {
        useType: "0",
        useReason: "0",
        staffUseTip: ""
      },
      isShowTable: true, //是否展示table
      isButtonLoading: false
    };
  },
  computed: {
    columnData() {
      if (this.tableData[0] && this.tableData[0].allStaffSchedulingVoList) {
        this.isShowTable = true;
        return this.tableData[0].allStaffSchedulingVoList;
      } else {
        this.isShowTable = false;
        return [];
      }
    }
  },
  methods: {
    async getCityAndBusinessOptions() {
      // 获取城市商圈枚举
      const { data } = await this.$http({
        url: "/hsssystemadmin/v1/businessManagement/getCityAreaList",
        method: "get"
      });
      if (data.length == 0) {
        this.$message.error("城市和商圈枚举获取失败");
      }
      this.cityAndBusinessOptions = data;
      this.chooseCityCode = this.cityAndBusinessOptions.find(
        item => item.cityName == "上海市"
      ).cityCode;
    },
    getBusinessOptions() {
      if (!this.chooseCityCode) {
        this.$message.error("请先选择城市");
        return false;
      }
      this.currentBusinessOptions = this.cityAndBusinessOptions.find(
        item => item.cityCode == this.chooseCityCode
      ).areas;
    },
    changeCityCode() {
      this.chooseBusinessCode = "";
      this.currentBusinessOptions = [];
    },
    async searchTable() {
      this.isloading = true;
      const paramsData = {
        query: "0",
        day: this.daystarttime,
        staffName: this.staffName,
        staffPhone: this.staffPhone,
        cityCode: this.chooseCityCode,
        businessCode: this.chooseBusinessCode,
        staffCode: this.staffCode
      };
      await this.$http({
        url: "/staffadmin/homeService/staffManager/getStaffSchedulingList",
        method: "get",
        params: paramsData
      })
        .then(res => {
          const { data } = res;
          this.tableData = data;
          if (this.tableData.length == 0) {
            this.isloading = false;
            return false;
          }
          this.checkArray = [];
          this.tableData.forEach(item => {
            this.checkArray.push(oneCheckItem);
          });
          // 回显之前选择的勾选(特殊处理 只做一个的  两个的不做)
          if (this.staffRestTimeArray.length == 1) {
            const staffCode = this.staffRestTimeArray[0].staffCode;
            const dateAndTime = `${this.staffRestTimeArray[0].date} ${this.staffRestTimeArray[0].time}`;
            const rowIndex = this.tableData.findIndex(
              item => item.staffCode == staffCode
            );
            const columnIndex = this.tableData[
              rowIndex
            ].allStaffSchedulingVoList.findIndex(
              item => item.timeDay == dateAndTime
            );
            if (rowIndex >= 0 && columnIndex >= 0) {
              // 找到了对应的位置节点  变更checkArray
              const oneList = JSON.parse(
                JSON.stringify(this.checkArray[rowIndex])
              );
              oneList[columnIndex].checked = true;
              this.checkArray.splice(rowIndex, 1, oneList);
            }
          }
          this.isloading = false;
        })
        .catch(err => {
          console.log(err);
          this.isloading = false;
        });
    },
    dayPrev() {
      const daystarttime = moment(new Date(this.daystarttime))
        .subtract(1, "days")
        .format("YYYY-MM-DD");
      this.daystarttime = daystarttime;
      this.searchTable();
    },
    dayNext() {
      const daystarttime = moment(new Date(this.daystarttime))
        .add(1, "days")
        .format("YYYY-MM-DD");
      this.daystarttime = daystarttime;
      this.searchTable();
    },
    changeTrStyle({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex;
      column.index = columnIndex;
    },
    cellClick(row, column, cell, event) {
      // console.log(row.index, column.index)
    },
    async changeCheckBoxValue(event, rowIndex, columnIndex) {
      // console.log(event.target.checked, rowIndex, columnIndex)
      if (event.target.checked) {
        const obj = {};
        obj.staffCode = this.tableData[rowIndex].staffCode;
        obj.staffName = this.tableData[rowIndex].staffName;
        obj.date = this.daystarttime;
        obj.time = this.tableData[rowIndex].allStaffSchedulingVoList[
          columnIndex
        ].day;
        if (this.staffRestTimeArray.length < 2) {
          if (this.staffRestTimeArray.length == 0) {
            // 勾选开始时间
            let textInfo = `<p>开始时间：${obj.date} ${obj.time}</p>
            <p>是否选择该时间点作为开始时间？</p>
            `;
            this.$confirm(textInfo, "确认开始时间", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              dangerouslyUseHTMLString: true
            }).then(() => {
              this.staffRestTimeArray.push(obj);
              const oneList = JSON.parse(
                JSON.stringify(this.checkArray[rowIndex])
              );
              oneList[columnIndex].checked = true;
              this.checkArray.splice(rowIndex, 1, oneList);
            });
          }
          if (this.staffRestTimeArray.length == 1) {
            // 勾选结束时间
            let textInfo = `<p>结束时间：${obj.date} ${obj.time}</p>
            <p>是否选择该时间点作为结束时间？</p>
            `;
            this.$confirm(textInfo, "确认结束时间", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              dangerouslyUseHTMLString: true
            }).then(async () => {
              // 前端校验是否选择的是同一个员工
              if (this.staffRestTimeArray[0].staffCode != obj.staffCode) {
                this.$message.error("请选择同一个员工的开始时间和结束时间");
                return false;
              }
              // 前端校验是否开始时间小于结束时间
              const startDateTime = moment(
                `${this.staffRestTimeArray[0].date} ${this.staffRestTimeArray[0].time}`
              );
              const endDateTime = moment(`${obj.date} ${obj.time}`);
              const diffTime = endDateTime.diff(startDateTime);
              console.log(diffTime);
              if (diffTime <= 0) {
                this.$message.error("选择的开始时间不能大于等于结束时间");
                this.checkArray = [];
                this.tableData.forEach(item => {
                  this.checkArray.push(oneCheckItem);
                });
                this.staffRestTimeArray = [];
                return false;
              }
              // 后端校验接口
              const validateFlag = await this.validate(obj);
              if (!validateFlag) {
                // 校验不通过触发
                this.$message.error(
                  "所选时间与开始时间之间不连续，请重新选择!"
                );
                this.staffRestTimeArray = [];
                this.checkArray = [];
                this.tableData.forEach(item => {
                  this.checkArray.push(oneCheckItem);
                });
                return false;
              }
              this.staffRestTimeArray.push(obj);
              const oneList = JSON.parse(
                JSON.stringify(this.checkArray[rowIndex])
              );
              oneList[columnIndex].checked = true;
              this.checkArray.splice(rowIndex, 1, oneList);
              // 确认弹框
              setTimeout(() => {
                this.confirmDialogShow = true;
              }, 1000);
            });
          }
        } else {
          const oneList = JSON.parse(JSON.stringify(this.checkArray[rowIndex]));
          oneList[columnIndex].checked = false;
          this.checkArray.splice(rowIndex, 1, oneList);
        }
      } else {
        const oneList = JSON.parse(JSON.stringify(this.checkArray[rowIndex]));
        oneList[columnIndex].checked = false;
        this.checkArray.splice(rowIndex, 1, oneList);
        const staffCode = this.tableData[rowIndex].staffCode;
        const findIndex = this.staffRestTimeArray.findIndex(
          item => item.staffCode == staffCode
        );
        this.staffRestTimeArray.splice(findIndex, 1);
      }
    },
    closedConfirmDialog() {
      // 确认弹框取消按钮
      this.staffRestTimeArray = [];
      this.checkArray = [];
      this.tableData.forEach(item => {
        this.checkArray.push(oneCheckItem);
      });
      this.form = {
        useType: "0",
        useReason: "0",
        staffUseTip: ""
      };
      this.confirmDialogShow = false;
    },
    async validate(obj) {
      let flag = false;
      const startTime = `${this.staffRestTimeArray[0].date} ${this.staffRestTimeArray[0].time}`;
      const endTime = `${obj.date} ${obj.time}`;
      const paramsData = {
        query: "0",
        staffCode: this.staffRestTimeArray[0].staffCode,
        startTime,
        endTime
      };
      const res = await this.$http({
        url: "/staffadmin/homeService/staffManager/staffSchedulingTimeCheck",
        method: "get",
        params: paramsData
      });
      const { data } = res;
      const keys = Object.keys(data);
      if (keys[0] == "0") {
        flag = false;
      }
      if (keys[0] == "1") {
        flag = true;
      }
      return flag;
    },
    clearData() {
      this.$router.replace({
        path: "/staffUse"
      });
      this.reload();
    },
    async updateStaffSchedulingLeave() {
      if (this.isButtonLoading) {
        return false;
      }
      // 请假保存接口
      let weeks = this.staffRestTimeArray.map(item => item.date);
      if (weeks.length == 2) {
        weeks = getAllDate(weeks[0], weeks[1]);
      }
      if (weeks.length >= 0) {
        weeks = Array.from(new Set(weeks));
        let trimStr = "";
        weeks.forEach((item, index) => {
          if (index == 0) {
            trimStr += `${item}`;
          }
          if (index != 0) {
            trimStr += `,${item}`;
          }
        });
        weeks = trimStr;
      }
      const params = {
        weeks,
        startTimeLeave: `${this.staffRestTimeArray[0].date} ${this.staffRestTimeArray[0].time}`,
        endTimeLeave: `${this.staffRestTimeArray[1].date} ${this.staffRestTimeArray[1].time}`,
        staffCode: this.staffRestTimeArray[0].staffCode,
        takeUpType: this.form.useType, // 请假占用类型
        takeUpReason: this.form.useReason, // 请假占用原因
        remark: this.form.staffUseTip, // 备注
        realName: this.staffRestTimeArray[0].staffName // 员工姓名
      };
      this.isButtonLoading = true;
      setTimeout(() => {
        this.isButtonLoading = false;
      }, 3000);
      await this.$http({
        url: "/staffadmin/homeService/staffManager/updateStaffSchedulingLeave",
        method: "get",
        params
      })
        .then(res => {
          const { success } = res;
          if (success == 1) {
            // 保存成功
            this.$message.success("员工请假数据保存成功");
            // this.$router.go(0)
            // 回到请假开始时间页面
            this.daystarttime = this.staffRestTimeArray[0].date;
            this.searchTable();
            this.staffRestTimeArray = [];
            this.confirmDialogShow = false;
            this.isButtonLoading = false;
          } else {
            this.$message.error("系统繁忙，请稍后重试");
          }
        })
        .catch(err => {
          this.$message.error("系统繁忙，请稍后重试");
        });
    }
  },
  activated() {
    const { daystarttime } = getToday();
    this.daystarttime = daystarttime;
    // 获取当前员工的code
    if (this.$route.query.staffCode) {
      this.staffCode = this.$route.query.staffCode;
    }
    const promise = this.getCityAndBusinessOptions();
    promise.then(res => {
      this.searchTable();
    });
  }
};
</script>

<style lang="scss" scoped>
.contentView {
  padding: 20px 20px 0 20px;
}
.contentBox {
  // padding: 0 10px;
  border: 10px solid #ebeef1;
  border-radius: 10px;
}
.herdertop {
  height: 8vh;
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-sizing: border-box;
  .topImg {
    margin-right: 20px;
  }
}
.tableTop1 {
  padding: 0 32px 0 32px;
  height: 56px;
  line-height: 56px;
  border: 1px solid #e9e9e9;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .top1Left {
    font-size: 20px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 900;
    color: rgba(0, 0, 0, 0.85);
  }
}
/deep/ .tableTop2 {
  font-size: 12px;
  font-weight: 500;
  border-left: 1px solid #e9e9e9;
  border-right: 1px solid #e9e9e9;
  height: 56px;
  line-height: 56px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .top2left {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .day {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin-right: 20px;
    }
  }
  .top2right {
    // margin-right: 30px;
  }
  .chooseCity,
  .chooseBusiness {
    .el-input__inner {
      font-size: 12px;
      height: 32px;
      width: 100px;
      padding-left: 8px;
    }
    .el-input__icon {
      line-height: 32px;
      height: 32px;
    }
    .el-popper[x-placement^="bottom"] {
      margin-top: -6px !important;
      .el-select-dropdown__empty {
        line-height: 18px;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
/deep/ .staffInput {
  height: 56px;
  width: 110px;
  .el-input__inner {
    height: 32px;
    width: 110px;
    padding: 0 10px;
  }
}
/deep/ .staffInput1 {
  height: 56px;
  width: 100px;
  .el-input__inner {
    height: 32px;
    width: 90px;
    padding: 0 10px;
  }
}
/deep/ .searchButton {
  padding-top: 7px;
  padding-bottom: 7px;
  // margin-left: 15px;
}
/deep/ .table3 {
  font-size: 12px;
  font-weight: 400;
  .cell {
    padding-left: 0;
    padding-right: 0;
  }
  .cell.el-tooltip {
    width: 100%;
    height: 100%;
    min-width: 40px;
    div {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .three {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        .ant-checkbox {
          display: block;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          height: 100%;
          .ant-checkbox-input {
            width: 20px;
            height: 20px;
            border-radius: 10px;
          }
        }
      }
    }
  }
}
/deep/ .el-table tr td {
  height: 37px;
  padding-top: 0;
  padding-bottom: 0;
}
/deep/ .el-table tr th {
  height: 37px;
  padding-top: 0;
  padding-bottom: 0;
}

/deep/ .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
  top: 3px;
  left: 6px;
  width: 5px;
  height: 8px;
  border-color: #fff;
}

/deep/ .staffUseElForm {
  .el-form-item {
    margin-bottom: 0;
  }
}

/deep/ .el-dialog__body {
  padding: 20px 20px;
}
.nomessage {
  height: 56px;
  font-size: 12px;
  // border-top: 1px solid #e9e9e9;
  line-height: 56px;
  text-align: center;
}
</style>
